package RockPaperScissors.GameFlow
{
    import RockPaperScissors.ProcessorStep;
    import RockPaperScissors.Utilities;
    
    import com.adobe.serialization.json.*;
    
    import mx.rpc.events.FaultEvent;
    import mx.rpc.events.ResultEvent;
    import mx.rpc.http.HTTPService;

    public class Outcome extends ProcessorStep
    {
        var results = {"contestant1":null, "contestant2":null};
        
        public function Outcome(onComplete:Function=null, onFail:Function=null)
        {
            super(onComplete, onFail);
            this.setupProcessorStep(onComplete, onFail);
        }
        
        public override function Process(data)
        {
            //Get the last round's results
            var last_round = data["rounds"][data["rounds"].length-1];
            
            var service:HTTPService = new HTTPService();
            
            var contestant1_uri = data["contestant1"]["uri"] + "/outcome";
            service.url = contestant1_uri;
            service.addEventListener(FaultEvent.FAULT, onFail);
            service.addEventListener(ResultEvent.RESULT, 
                Utilities.createCallBack(this.onComplete, {"contestant":"contestant1", "data":data, "context":this}));
            service.method = "POST";
            service.send({"data":JSON.encode(last_round)});
            
            service = new HTTPService();
            var contestant2_uri = data["contestant2"]["uri"] + "/outcome";
            service.url = contestant2_uri;
            service.addEventListener(FaultEvent.FAULT, onFail);
            service.addEventListener(ResultEvent.RESULT, 
                Utilities.createCallBack(this.onComplete, {"contestant":"contestant2", "data":data, "context":this}));
            service.method = "POST";
            service.send({"data":JSON.encode(last_round)});
        }
        
        public function onComplete(event:ResultEvent, data)
        {
            var result = event.result;
            var contestant_name:String = data["contestant"];
            results[contestant_name] = result;
            
            if(results["contestant1"] != null && results["contestant2"] != null)
            {
                data["data"]["on_score_updated"](data["data"]);
                this.ProcessingComplete(data["data"]);
            } 
        }
        
        public function onFail(event:FaultEvent)
        {
            var msg = event.message;
        }
        
    }
}